<?php

/**
 * 管理后台
 * 
 * @author ShuangYa
 * @package Blog
 * @category Controller
 * @link http://www.sylingd.com/
 * @copyright Copyright (c) 2015 ShuangYa
 * @license http://lab.sylingd.com/go.php?name=blog&type=license
 */

use \sy\base\Controller;
use \sy\base\i18n;
use \sy\lib\YHtml;
use \sy\lib\YMysql;
use \sy\lib\YSecurity;
use \sy\lib\YCookie;
use \sy\tool\YFtp;
use \blog\libs\option;
use \blog\libs\BArticle;
use \blog\libs\BMeta;
use \blog\libs\BLink;

class CAdmin extends Controller {
	protected $password;
	public function __construct() {
		//强制不缓存
		header('expires: ' . date('d,d m y h:i:s', mktime(0, 0, 0, 1, 1, 2000)) . ' gmt');
		header('last-modified:' . gmdate('d,d m y h:i:s') . ' gmt');
		header('cache-control: private, no-cache,must-revalidate');
		header('pragma: no-cache');
		$this->password = option::get('password');
	}
	/**
	 * 检查登录状态
	 * @access protected
	 */
	protected function checkLogin($error = '') {
		if (isset($_REQUEST['auth'])) {
			$auth = $_REQUEST['auth'];
		} else {
			$auth = YCookie::get('auth');
		}
		if ($auth !== md5($this->password)) {
			switch ($error) {
				case 'boolean':
					return TRUE;
				case 403:
					Sy::httpStatus('403', TRUE);
				default:
					Sy::setMimeType('html');
					echo '<script type="text/javascript">window.location.href="' . Sy::createUrl('admin/login') . '";</script><a href="' . Sy::createUrl('admin/login') . '">Click here!</a>';
					exit;
			}
		} else {
			if (!isset($_REQUEST['auth'])) {
				YCookie::set(['name' => 'auth', 'value' => $auth, 'httponly' => TRUE]);
			}
			return TRUE;
		}
	}
	/**
	 * Home
	 */
	public function actionHome() {
		$this->checkLogin();
		Sy::setMimeType('html');
		Sy::view('admin/home');
	}
	/**
	 * 登录
	 */
	public function actionLogin() {
		Sy::setMimeType('html');
		if (isset($_POST['password'])) {
			if (YSecurity::password($_POST['password']) === $this->password) {
				YCookie::set(['name' => 'auth', 'value' => md5($this->password), 'httponly' => TRUE]);
				echo 1;
			} else {
				echo 0;
			}
		} else {
			if (!empty($_SERVER['HTTP_REFERER'])) {
				$redirect = $_SERVER['HTTP_REFERER'];
			} else {
				$redirect = Sy::createUrl('admin/home');
			}
			$redirect = addslashes($redirect);
			Sy::view('admin/login', ['redirect' => $redirect]);
		}
	}
	/**
	 * 退出
	 */
	public function actionLoginout() {
		YCookie::set(['name' => 'auth', 'value' => 'v', 'expire' => -1, 'httponly' => TRUE]);
		header('Location: ' . Sy::createUrl('admin/login'));
	}
	/**
	 * 选项
	 */
	public function actionOption() {
		$this->checkLogin();
		Sy::setMimeType('html');
		Sy::view('admin/option/basic');
	}
	/**
	 * 保存选项
	 */
	public function actionOptionSave() {
		$this->checkLogin('403');
		foreach ($_POST as $k => $v) {
			if (substr($k, 0, 3) === 'op_') {
				$k = substr($k, 3);
				if ($k === 'pagesize') {
					$v = intval($v);
				}
				option::set($k, $v);
			}
		}
		echo json_encode(['success' => 1]);
	}
	/**
	 * 修改密码
	 */
	public function actionOptionPassword() {
		$this->checkLogin();
		if (isset($_POST['ajax'])) {
			Sy::setMimeType('json');
			$old = $_POST['old'];
			$new = $_POST['new'];
			if (strlen($new) < 5) {
				echo json_encode(['success' => 0, 'message' => i18n::get('password_mustnt_less_than_5_char')]);
				exit;
			}
			if (YSecurity::password($old) !== $this->password) {
				echo json_encode(['success' => 0, 'message' => i18n::get('old_password_wrong')]);
				exit;
			}
			$this->password = YSecurity::password($new);
			option::set('password', $this->password);
			YCookie::set(['name' => 'auth', 'value' => md5($this->password), 'httponly' => TRUE]);
			echo json_encode(['success' => 1]);
		} else {
			Sy::setMimeType('html');
			Sy::view('admin/option/password');
		}
	}
	/**
	 * SEO选项
	 */
	public function actionOptionSeo() {
		$this->checkLogin();
		Sy::setMimeType('html');
		Sy::view('admin/option/seo');
	}
	public function actionOptionSeoSave() {
		$this->checkLogin(403);
		Sy::setMimeType('json');
		$enable = ($_POST['enable'] == 1 ? TRUE : FALSE);
		switch ($_POST['_type']) {
			case 'ping':
				option::set('seoPing', str_replace("\r", '', $_POST['ping']));
				echo json_encode(['success' => 1]);
				break;
			case 'baidusubmit':
				option::set('seoBaiduSubmit', serialize(['enable' => $enable, 'site' => $_POST['site'], 'token' => $_POST['token']]));
				echo json_encode(['success' => 1]);
				break;
			case 'sitemap':
				option::set('seoSitemap', serialize(['enable' => $enable, 'type' => $_POST['type'], 'changefreq' => $_POST['changefreq']]));
				echo json_encode(['success' => 1]);
				break;
			default:
				echo json_encode(['success' => 0, 'message' => i18n::get('unknow_operation')]);
				break;
		}
	}
	public function actionOptionSeoSitemap() {
		$sitemap = new \blog\libs\Sitemap();
		$sitemap->mk();
		echo json_encode(['success' => 1]);
	}
	/**
	 * 文章
	 */
	public function actionArticle() {
		$this->checkLogin();
		if (isset($_POST['ajax'])) {
			Sy::setMimeType('json');
			$page = (isset($_POST['page']) && $_POST['page'] > 0) ? (intval($_POST['page'] - 1)) : 0;
			$start = $page * 30;
			$list = BArticle::getList(['body' => FALSE, 'limit' => $start . ',30'])->getAll();
			$num = BArticle::getNum();
			echo json_encode(['success' => 1, 'count' => $num, 'list' => $list]);
		} else {
			Sy::setMimeType('html');
			Sy::view('admin/content/article');
		}
	}
	/**
	 * Ajax修改文章
	 */
	public function actionAjaxArticleEdit() {
		$this->checkLogin('403');
		Sy::setMimeType('json');
		if (empty($_POST['title'])) {
			echo json_encode(['success' => 0, 'message' => i18n::get('title_can_not_be_empty')]);
			exit;
		}
		$time = strtotime($_POST['time']);
		BArticle::set($_POST['id'], $_POST['title'], $_POST['tags'], $time);
		echo json_encode(['success' => 1, 'time' => $time]);
	}
	/**
	 * Ajax删除文章
	 */
	public function actionAjaxArticleDel() {
		$this->checkLogin('403');
		Sy::setMimeType('json');
		BArticle::del($_POST['id']);
		echo json_encode(['success' => 1]);
	}
	/**
	 * 编辑文章
	 */
	public function actionArticleWrite() {
		$this->checkLogin();
		if (isset($_POST['title'])) {
			Sy::setMimeType('json');
			if (empty($_POST['title'])) {
				echo json_encode(['success' => 0, 'message' => i18n::get('title_can_not_be_empty')]);
				exit;
			}
			if (isset($_POST['id'])) {
				BArticle::set($_POST['id'], $_POST['title'], $_POST['tags'], strtotime($_POST['time']), $_POST['body']);
			} else {
				BArticle::add($_POST['title'], $_POST['tags'], strtotime($_POST['time']), $_POST['body']);
			}
			echo json_encode(['success' => 1]);
		} else {
			Sy::setMimeType('html');
			if (isset($_GET['id']) && !empty($_GET['id'])) {
				$id = intval($_GET['id']);
				$article = BArticle::get($id);
				$data = ['title' => '编辑文章', 'page' => 'ArticleEdit', 'id' => $id, 'article' => $article];
			} else {
				$data = ['title' => '撰写文章', 'page' => 'ArticleNew', 'id' => $id, 'article' => $article];
			}
			Sy::view('admin/content/articleWrite', $data);
		}
	}
	/**
	 * 标签
	 */
	public function actionMeta() {
		$this->checkLogin();
		if (isset($_POST['ajax'])) {
			Sy::setMimeType('json');
			$page = (isset($_POST['page']) && $_POST['page'] > 0) ? (intval($_POST['page'] - 1)) : 0;
			$start = $page * 30;
			$num = BMeta::getNum();
			$list = BMeta::getList(['limit' => $start . ',30'])->getAll();
			echo json_encode(['success' => 1, 'count' => $num, 'list' => $list]);
		} else {
			Sy::setMimeType('html');
			Sy::view('admin/content/meta');
		}
	}
	/**
	 * Ajax修改标签
	 */
	public function actionAjaxMetaEdit() {
		$this->checkLogin('403');
		Sy::setMimeType('json');
		if (empty($_POST['title'])) {
			echo json_encode(['success' => 0, 'message' => i18n::get('title_can_not_be_empty')]);
			exit;
		}
		BMeta::set($_POST['id'], $_POST['title'], $_POST['type']);
		echo json_encode(['success' => 1]);
	}
	/**
	 * Ajax查找标签
	 */
	public function actionAjaxMetaGet() {
		$this->checkLogin('403');
		Sy::setMimeType('json');
		if (empty($_POST['title'])) {
			echo json_encode(['success' => 1, 'list' => []]);
			exit;
		}
		$list = BMeta::getList(['title' => $_POST['title'], 'limit' => '0,5'])->getAll();
		echo json_encode(['success' => 1, 'list' => $list]);
	}
	/**
	 * 链接
	 */
	public function actionLink() {
		$this->checkLogin();
		if (isset($_POST['ajax'])) {
			Sy::setMimeType('json');
			$page = (isset($_POST['page']) && $_POST['page'] > 0) ? (intval($_POST['page'] - 1)) : 0;
			$start = $page * 30;
			$list = BLink::getList(['limit' => $start . ',30'])->getAll();
			$num = BLink::getNum();
			echo json_encode(['success' => 1, 'count' => $num, 'list' => $list]);
		} else {
			Sy::setMimeType('html');
			Sy::view('admin/link');
		}
	}
	/**
	 * Ajax删除链接
	 */
	public function actionAjaxLinkDel() {
		$this->checkLogin(403);
		Sy::setMimeType('json');
		BLink::del($_POST['id']);
		echo json_encode(['success' => 1]);
	}
	/**
	 * Ajax增加链接
	 */
	public function actionAjaxLinkAdd() {
		$this->checkLogin('403');
		Sy::setMimeType('json');
		BLink::add($_POST['title'], $_POST['rel'], $_POST['url']);
		echo json_encode(['success' => 1]);
	}
	/**
	 * Ajax修改链接
	 */
	public function actionAjaxLinkEdit() {
		$this->checkLogin(403);
		Sy::setMimeType('json');
		BLink::set($_POST['id'], $_POST['title'], $_POST['rel'], $_POST['url']);
		echo json_encode(['success' => 1]);
	}
	/**
	 * 附件选项
	 */
	public function actionOptionAttachment() {
		$this->checkLogin();
		$this->load_model('attachment', 'att');
		if (isset($_POST['type'])) {
			Sy::setMimeType('json');
			$type = $_POST['type'];
			option::set('attachmentType', $type);
			option::set('attachmentFormat', $_POST['format']);
			option::set('attachmentSize', $_POST['size']);
			if ($type !== 'local') {
				option::set('attachmentUrl', $_POST['url']);
				$backup = $_POST['backup'];
				option::set('attachmentBackup', $backup);
				if ($backup == 1) {
					option::set('attachmentBackupFormat', $_POST['backupFormat']);
				}
				$this->att->remoteDo($type, 'config', [$_POST[$type]]);
			}
			echo json_encode(['success' => 1]);
		} else {
			Sy::setMimeType('html');
			$support = $this->att->getRemoteSupport();
			$config = [];
			foreach ($support as $k => $v) {
				$config[$k] = $this->att->remoteDo($k, 'getForm');
			}
			Sy::view('admin/option/attachment', ['support' => $support, 'config' => $config]);
		}
	}
	/**
	 * 附件上传
	 */
	public function actionAttachmentUpload() {
		$this->checkLogin(403);
		$this->load_model('attachment', 'att');
		Sy::setMimeType('json');
		//允许跨域调用
		header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET,POST,OPTIONS');
        header('Access-Control-Allow-Headers: Cache-Control,X-Requested-With,Content-Type');
		if (empty($_FILES)) {
			echo json_encode(['message' => i18n::get('$_FILES_is_empty')]);
			exit;
		}
		reset($_FILES);
		$f = current($_FILES);
		if (!$this->att->check($f)) {
			echo json_encode(['message' => i18n::get('illegal_request')]);
			exit;
		}
		$attachmentType = option::get('attachmentType');
		//生成目标名称
		$f_info = pathinfo($f['name']);
		$save = $this->att->getName(option::get('attachmentFormat'), $f_info['extension']);
		$remote_info = pathinfo($save);
		$r = $this->att->add($f, $save);
		//本地备份
		if ($attachmentType !== 'local' && option::get('attachmentBackup') == 1) {
			$local_name = $this->att->getName(option::get('attachmentBackupFormt'), $f_info['extension'], FALSE);
			$local_name = str_replace('{{file}}', $remote_info['basename'], $local_name);
			$this->att->local($f['tmp_name'], $local_name);
		}
		if ($r !== FALSE) {
			list($id, $type, $url) = $r;
			echo json_encode(['id' => $id, 'type' => $type, 'url' => $url]);
		} else {
			echo json_encode(['message' => '上传文件失败']);
		}
	}
	/**
	 * base64方式上传图片
	 */
	public function actionAttachmentUploadBase64() {
		$this->checkLogin(403);
		$base64Data = $_POST['base64Data'];
		if (substr($base64Data, 0, 22) !== 'data:image/png;base64,') {
			echo json_encode(['message' => i18n::get('illegal_request')]);
		}
		$tmp_name = \blog\getTempName();
		file_put_contents($tmp_name, base64_decode(substr($base64Data, 22)));
		$_FILES = [
			'img' => [
				'name' => 'a.png',
				'type' => Sy::getMimeType('png'),
				'size' => filesize($tmp_name),
				'tmp_name' => $tmp_name,
				'error' => UPLOAD_ERR_OK
			]
		];
		$this->actionAttachmentUpload();
		@unlink($tmp_name);
	}
	/**
	 * 修改附件信息
	 */
	public function actionAttachmentEdit() {
		$this->checkLogin(403);
		$this->load_model('attachment', 'att');
		Sy::setMimeType('json');
		if (empty($_POST['name'])) {
			echo json_encode(['message' => '名称不能为空']);
			exit;
		}
		$type = $this->att->setName($_POST['id'], $_POST['name']);
		echo json_encode(['success' => 1,'type' => $type]);
	}
	/**
	 * 附件管理
	 */
	public function actionAttachmentManage() {
		$this->checkLogin();
		Sy::setMimeType('html');
		Sy::view('admin/content/attachment');
	}
	/**
	 * 获取附件列表
	 */
	public function actionAttachmentList() {
		$this->checkLogin(403);
		Sy::setMimeType('json');
		$lastid = intval($_POST['id']);
		$sql = 'SELECT * FROM `#@__attachment` WHERE id < ? ORDER BY id DESC LIMIT 0,20';
		YMysql::_i()->query('attachment', $sql, [$lastid]);
		$list = YMysql::_i()->getAll('attachment');
		end($list);
		$last = current($list);
		echo json_encode(['success' => 1, 'lastId' => $last['id'], 'list' => $list]);
	}
	/**
	 * 删除附件
	 */
	public function actionAttachmentDel() {
		$this->checkLogin(403);
		$this->load_model('attachment', 'att');
		Sy::setMimeType('json');
		$r = $this->att->del($_POST['id']);
		echo json_encode(['success' => ($r === TRUE ? 1 : 0)]);
	}
}
